/**
 * ReportGear(2011)
 */
package com.reportgear.report.view.grid.editor;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

import com.reportgear.report.context.ReportContext;
import com.reportgear.report.model.ReportModel;
import com.reportgear.report.view.JWorksheet;
import com.reportgear.report.view.grid.Grid;
import com.reportgear.report.view.grid.selection.GridSelection;
import com.reportgear.report.view.grid.selection.Selection;

/**
 * 单元格编辑操作
 * 
 * @version 1.0 2011-6-4
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class CellEditAction extends AbstractAction {
	/**
	 * UID
	 */
	private static final long serialVersionUID = 8816223974830744750L;
	// 元素对象类
	private Class<?> cellElementClazz;

	public CellEditAction(String name, Class<?> cellElementClazz) {
		super(name);

		this.cellElementClazz = cellElementClazz;
	}

	public void actionPerformed(ActionEvent e) {
		JWorksheet worksheet = ReportContext.INSTANCE.getCurrentWorkSheet();
		if (worksheet == null) {
			return;
		}

		GridSelection gridSel = worksheet.getGridSelection();
		Grid grid = worksheet.getGrid();
		if (grid.isCellSelectable()) {
			try {
				Selection sel = gridSel.getEditSelection();
				ReportModel report = worksheet.getReportModel();

				Object cellElement = report.getCell(sel).getValue();
				// 单元格对象为空或单元格类与新类不相同时，设置值为新类实例
				if ((cellElement == null) || (cellElementClazz != cellElement.getClass())) {
					report.setCellValue(sel, cellElementClazz.newInstance());
				}
				grid.startEditing();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}
